package org.daymr.sglandroid01;

import android.app.Activity;
import android.app.ActivityManager;
import android.content.Context;
import android.content.pm.ConfigurationInfo;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.Toast;

/**
 * 本节主要学习OpenGL ES 2.0的绘制方式
 * @author Ben
 * @date 2015年1月2日 上午12:25:35
 */
public class MainActivity extends Activity implements OnClickListener {

	/**自定义View*/
	public MyView mMyView; 
	/**渲染开关*/
	public boolean isRenderer;
	
	public Button mBt1,mBt2,mBt3;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		//去标题
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
				WindowManager.LayoutParams.FLAG_FULLSCREEN);
		
		if(supportES2()){//若支持OpenGL ES 2.0
			isRenderer = true;
		}else{//若不支持
			Toast.makeText(this, "设备不支持OpenGL ES 2.0 .", Toast.LENGTH_SHORT).show();
		}
		setContentView(R.layout.activity_main);
		
		initView();
	}
	
	/**
	 * 初始化控件
	 */
	public void initView(){
		mMyView =  (MyView) findViewById(R.id.myView);
		mBt1 = (Button) findViewById(R.id.button1);
		mBt1.setOnClickListener(this);
		mBt2 = (Button) findViewById(R.id.button2);
		mBt2.setOnClickListener(this);
		mBt3 = (Button) findViewById(R.id.button3);
		mBt3.setOnClickListener(this);
	}

	/**
	 * 判断是否支持OpenGL ES 2.0
	 * @return true则说明设备支持OpenGL ES 2.0，否则不支持
	 */
	private boolean supportES2(){
		ActivityManager am = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
		ConfigurationInfo cfi = am.getDeviceConfigurationInfo();
		return cfi.reqGlEsVersion>=0x20000
				|| (Build.VERSION.SDK_INT>=Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1
				&&(Build.FINGERPRINT.startsWith("generic")
						|| Build.FINGERPRINT.startsWith("unknown")
						|| Build.MODEL.contains("google_sdk")
						|| Build.MODEL.contains("Emulator")
						|| Build.MODEL.contains("Android SDK build for x86")));
	}

	
	@Override
	protected void onResume() {
		super.onResume();
		if(isRenderer)
			mMyView.onResume();
	}
	
	
	@Override
	protected void onPause() {
		super.onPause();
		if(isRenderer)
			mMyView.onPause();
	}

	@Override
	public void onClick(View v) {
		int id = v.getId();
		switch(id){
		case R.id.button1://GL_TRIANGLES
			mMyView.flag = 1;
			//手动刷新
			mMyView.requestRender();
			break;
		case R.id.button2://GL_TRIANGLE_STRIP
			mMyView.flag = 2;
			mMyView.requestRender();
			break;
		case R.id.button3://GL_TRIANGLE_FAN
			mMyView.flag = 3;
			mMyView.requestRender();
			break;
		}
	}

}
